<template>
  <div>
    <Page auto-content-height>
      <!-- 搜索条件 -->
      <div class="bg-card mb-4 rounded-lg px-4 pt-6">
        <BaseForm />
      </div>
      <FosoTable
        :tool-bar-button-text="$t('sys.department.addDepartment')"
        table-title="部门管理"
        table-titlehelp="职位管理帮助"
        @add="openDrawerHandle('add', $event)"
      >
        <!-- 状态列 -->
        <template #status="{ row }">
          <StatusColumn :request-api="updateDepartment" :row="row" />
        </template>
        <!-- 操作列 -->
        <template #action="{ row }">
          <OperationColumn
            :row="row"
            @delete="DeleteHandle(row)"
            @edit="openDrawerHandle('edit', $event)"
          />
        </template>
      </FosoTable>
      <!-- 表格 -->
      <!-- 弹窗框 -->
    </Page>
    <Drawer class="w-[35%]" destroy-on-close="true" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import { Page, useVbenDrawer, useVbenForm } from '@vben/common-ui';
import { $t } from '@vben/locales';

import {
  deleteDepartment,
  getDepartmentList,
  updateDepartment,
} from '#/api/sys/department';
import { type DepartmentInfo } from '#/api/sys/model/departmentModel';
import { OperationColumn } from '#/components/FosoTablePro/index';
import { useFosoTable } from '#/components/FosoTablePro/use-foso-config';
import { useFosoTableConfig } from '#/components/FosoTablePro/use-foso-table';

import ExtraDrawer from './components/drawer.vue';
import { tableColumns } from './schemas';
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});

// 使用 useFosoTable hook 生成配置
const { gridOptions } = useFosoTableConfig({
  columns: tableColumns,
  requestApi: getDepartmentList,
  treeConfig: {
    transform: true, // 自动将 parentId 转换为树形结构
    parentField: 'parentId', // 父节点字段名
    rowField: 'id', // 行数据字段名
    lazy: false, // 非懒加载
    indent: 20, // 缩进宽度
  },
});

const { FosoTable, FosoTableApi } = useFosoTable(gridOptions);

// 定义表单
const [BaseForm] = useVbenForm({
  // 默认展开
  collapsed: true,
  layout: 'horizontal',
  // 提交函数
  handleSubmit: searchHandle,
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-3',
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: $t('sys.department.departmentName'),
    },
    {
      component: 'Input',
      fieldName: 'leader',
      label: $t('sys.department.leader'),
    },
  ],
});

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {any} row - 要编辑的行数据对象，包含字典相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: DepartmentInfo): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.department.editDepartment') });
    drawerApi.setData({ type: 'editData', id: row.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.department.addDepartment') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 删除部门
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: DepartmentInfo): Promise<void> {
  await deleteDepartment(row.id as number);
  ElMessage.success($t('common.operateSuccess'));
  FosoTableApi.commitProxy('reload');
}

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  FosoTableApi.commitProxy('reload');
  drawerApi.close();
};

/**
 * @author Buke
 * @description 搜索字典
 * @returns {void}
 */
function searchHandle(values: Record<string, any>): void {
  FosoTableApi.commitProxy('query', values);
}
</script>
